import React from 'react';
import { Calendar, Icon } from 'antd';
import { formatDate, _str2Int } from '../../util/common';
import {WeaErrorPage, WeaTools, WeaNewScroll, WeaLocaleProvider} from 'ecCom';
const getLabel = WeaLocaleProvider.getLabel;
const { ls } = WeaTools;
//会议日历元素
class MeetingCalendarTemplate extends React.Component {
    constructor(props) {
        super(props);
        let _date = new Date();
        this.state = {
            refresh: false,
            weekStartDay:props.weekStartDay||0,
            data: props.data,
            createVisible: false,
            createType: 'create',
            currentDate: formatDate(_date, "yyyy-MM-dd"),
            currentMonth: formatDate(_date, "yyyy-MM"),
            activeKey: '1',
            meetingId: '',
            RoomPlanContainer:false,
            meetingtype: '0',
            weaMeetingLoaded: false,
            type: 'month',
            selectYear: formatDate(_date, "yyyy"),
            firstDay: formatDate(_date, "yyyy-MM-dd")
        }
        this.doAdd = this.doAdd.bind(this);
        this.onClose = this.onClose.bind(this);
        this.onClickData = this.onClickData.bind(this);
        this.dateCellRender = this.dateCellRender.bind(this);
        this.setAll = this.setAll.bind(this);
        this.setMeetingId = this.setMeetingId.bind(this);
        this.setRoomPlan = this.setRoomPlan.bind(this);
        this.setDialog = this.setDialog.bind(this);
        this.setType = this.setType.bind(this);
        this.doRefesh = this.doRefesh.bind(this);
        this.monthCellRender = this.monthCellRender.bind(this);
        this.clickMeetingCalendarMonth = this.clickMeetingCalendarMonth.bind(this);
        // if(window.window_clickMeetingCalendarDay){
        //     window.window_clickMeetingCalendarDay['fn'+props.eid] = this.clickMeetingCalendarDay.bind(this);
        // }else{
        //     let obj = {};
        //     obj['fn'+props.eid] = this.clickMeetingCalendarDay.bind(this);
        //     window.window_clickMeetingCalendarDay = obj;
        // }
        this.clickMeetingCalendarDay = this.clickMeetingCalendarDay.bind(this)
    }
    componentWillMount() {
        // 异步加载会议模块静态资源
        eventRegister.loadModule('f_meeting', ()=> {
            this.setState({weaMeetingLoaded:true});
        }, ()=> {});
    }
    componentWillReceiveProps(newProps) {
        this.setState({
            data: newProps.data,
            weekStartDay:newProps.weekStartDay
        })
    }
    onPanelChange(value, type, firstDay) {
        let selectYear = formatDate(new Date(), "yyyy");
        if(typeof value == 'object'){
            selectYear = value.fields[1];
        }
        this.setState({
            type,
            selectYear
        });
        const { meetingtype } = this.state;
        const { eid, hpid, subCompanyId } = this.props;
        var selectdate = "";
        if (typeof value === 'object') {
            var year = value.getYear();
            var month = value.getMonth() + 1 < 10 ? '0' + (value.getMonth() + 1) : value.getMonth() + 1;
            var currentMonth = year + '-' + month;
            selectdate = year + '-' + month + '-01';
            let _month = formatDate(new Date(), "yyyy-MM");
            if (selectdate === (_month + "-01")) {
                this.setState({
                    currentDate: formatDate(new Date(), "yyyy-MM-dd"),
                    currentMonth: _month,
                });
            } else {
                this.setState({
                    currentDate: selectdate,
                    currentMonth: year + '-' + month,
                });
            }
        } else {
            selectdate = value;
            this.setState({
                currentDate: selectdate,
            });
        }
        if(firstDay && type=='year') {
            selectdate = firstDay;
        }
        WeaTools.callApi('/api/meeting/calendar/getData', 'POST', {viewType: '3', selectdate: selectdate , meetingType: meetingtype }).then(data=> {
            ls.set('edata-'+eid, data);
            this.setState({
                data: data,
                refresh: false,
                weekStartDay:data.weekStartDay
            });
        });
    }
    // componentDidMount() {
    //     $("#calendar_" + this.props.eid + " .ant-fullcalendar-cell").attr("onclick", "window_clickMeetingCalendarDay['fn"+this.props.eid+"'](this)");
    // }

    shouldComponentUpdate(nextProps, nextState){
        // if(nextState.type == 'month' && this.state.type == 'year'){
        //     this.setState( {type: nextState.type},() => {$("#calendar_" + this.props.eid + " .ant-fullcalendar-cell").attr("onclick", "window_clickMeetingCalendarDay['fn"+this.props.eid+"'](this)")})
        // }else if(nextState.type == 'year' && this.state.type == 'month'){
        //     this.setState( {type: nextState.type},() => {$("#calendar_" + this.props.eid + " .ant-fullcalendar-month-panel-cell").attr("onclick", "window_clickMeetingCalendarDay['fn"+this.props.eid+"'](this)")})
        // }
        if(nextState.type == 'month' && this.state.type == 'year'){
            this.setState( {type: nextState.type})
        }else if(nextState.type == 'year' && this.state.type == 'month'){
            this.setState( {type: nextState.type})
        }
        if(nextState.weekStartDay!=this.state.weekStartDay){
             this.setState( {weekStartDay: nextState.weekStartDay})
        }
       
        return true;
    }
    doAdd(){
        this.setState({
            createVisible: true,
            createType: 'create'
        });
    }
    onClose(){
        this.setState({
            createVisible: false,
            activeKey: '1',
        });
    }
    onClickData(id){
        this.setState({
            createVisible: true,
            createType: 'preview',
            meetingId: id,
        });

    }
    setAll(meetingId, bool, type){
        this.setState({
            meetingId: meetingId,
            createVisible: bool,
            createType: type
        });
    }
    setMeetingId(meetingId) {
        this.setState({
            meetingId: meetingId
        });
    }
    setRoomPlan(bool){
        this.setState({
            RoomPlanContainer: bool
        });
    }
    setDialog(bool){
        this.setState({
            createVisible: bool
        });
        if(!bool){
            this.onPanelChange(this.state.currentDate, this.state.type, this.state.firstDay);
        }
    }
    setType(type){
        this.setState({
            createType: type
        });
    }
    doRefesh(){
        const { handleRefresh } = this.props;
        handleRefresh();
    }
    render() {
        const { eid, layoutid } = this.props;
        const { createVisible,weaMeetingLoaded, createType, currentDate, workPlanId, activeKey, data, meetingId,_date,RoomPlanContainer, type ,weekStartDay} = this.state;
        let createConditionParams = ['','',currentDate,formatDate(new Date(), "hh:mm"),currentDate,'23:59','0'];
        const getlocale ={
            firstDayOfWeek:weekStartDay,
        }
        return <div id={`calendar_${eid}`}>
            <Calendar locale={getlocale} ecId={`${this && this.props && this.props.ecId || ''}_Calendar@g5y26o`} onSelect={this.clickMeetingCalendarDay} fullscreen={false} onPanelChange={this.onPanelChange.bind(this)} monthCellRender={this.monthCellRender(eid)} value={new Date(currentDate)} dateCellRender={this.dateCellRender.bind(this,eid,data)}/>
            <CalendarData ecId={`${this && this.props && this.props.ecId || ''}_CalendarData@3s1igb`} data={data} firstDay={this.state.firstDay} type={type} currentDate={currentDate} handleClick={this.onClickData}/>
            <div className="portal-element-calender-add">
                <Icon ecId={`${this && this.props && this.props.ecId || ''}_Icon@0kthwj`} type="plus-circle-o" title={getLabel(611, '添加')} onClick={this.doAdd} />
            </div>
            {weaMeetingLoaded && window.weaMeeting && window.weaMeeting.com ? <window.weaMeeting.com.MeetingDialog ecId={`${this && this.props && this.props.ecId || ''}_MeetingDialog@ni56ol`}
                isCustom={true}
                setRoomPlan={this.setRoomPlan}
                setDialog={this.setDialog}
                setType={this.setType}
                doClose={this.onClose}//关闭回调
                setMeetingId={this.setMeetingId}
                setAll={this.setAll}
                type={createType}//新建为'create',查看为'preview',编辑edit,会议决议---decision
                visible={createVisible}//显隐受控
                doRefesh={() => { this.doRefesh() }}//自定义刷新页面，不会关掉弹出框
                meetingId={createType == 'create' ? '' : meetingId} //会议id，查看会议时用到
                isInterval={false}//新建会议类型，true是周期会议， false是普通会议
                meetingDate={currentDate}//新建日期
            /> : ''}
            {weaMeetingLoaded && window.weaMeeting && window.weaMeeting.com ? <window.weaMeeting.com.MeetingRoomPlan ecId={`${this && this.props && this.props.ecId || ''}_MeetingRoomPlan@hzpmjt`}
                isCustom={true}
                setRoomPlan={this.setRoomPlan}
                canCreate={false}
                height={600}
                visible={RoomPlanContainer} />: ''}
        </div>
    }
    dateCellRender(eid, data, value){
        const { currentDate, currentMonth } = this.state;
        $("#calendar_" + eid).find(".ant-fullcalendar-current").removeClass("ant-fullcalendar-current");
        $("#calendar_" + eid).find(".ant-fullcalendar-event").removeClass("ant-fullcalendar-event");
        $("#calendar_"+eid).find(".ant-fullcalendar-current").removeClass("ant-fullcalendar-current");
        let dataStr1 = formatDate(new Date(value.time), 'yyyy-M-d');
        let dateStr = formatDate(new Date(value.time), 'yyyy-MM-dd');
        let events = this.state.data.events;
        let timer = setTimeout(()=>{
            events.map(arr => {
                let startDate = formatDate(new Date(arr.begindate), 'yyyy-MM-dd');
                let endDate = formatDate(new Date(arr.enddate), 'yyyy-MM-dd');
                if(dateStr >= startDate && dateStr <= endDate){
                    $("#calendar_" + eid + " .ant-fullcalendar-cell[title='" + dataStr1 + "'] .ant-fullcalendar-value").addClass("ant-fullcalendar-event");
                }
            });
            if(dateStr === currentDate){
                $("#calendar_" + eid + " .ant-fullcalendar-cell[title='" + dataStr1 + "'] .ant-fullcalendar-value").addClass("ant-fullcalendar-current");
            }
            clearTimeout(timer);
        },100);
    }

    monthCellRender(eid){
        $("#calendar_" + eid).find(".ant-fullcalendar-month-panel-selected-cell").removeClass("ant-fullcalendar-month-panel-current-cell");
        $("#calendar_" + eid + " .ant-fullcalendar-month-panel-selected-cell .ant-fullcalendar-month .ant-fullcalendar-value").css({border: '#2db7f5 solid 1px'});
    }

    clickMeetingCalendarDay(obj){
        const { currentDate, currentMonth,type } = this.state;
        const { eid } = this.props;
        if(type == 'year') {
            this.clickMeetingCalendarMonth(obj);
            return;
        }
        var title = formatDate(new Date(obj.time), "yyyy-MM-dd");
        var ndate = "";
        var currentMonthStr =  "";
        if(title) {
            var titlearr =  title.split("-");
            ndate = titlearr[0];
            currentMonthStr = titlearr[0];
            ndate = ndate + "-" + titlearr[1];
            currentMonthStr = currentMonthStr + "-"+titlearr[1];
            ndate = ndate + "-" + titlearr[2];

        }
        if(ndate){
            this.setState({
                currentDate: ndate,
            });
        }
        //判断点击的是否为当前显示月份，否的话刷新新月份的日历日程，并默认选中所点击的日期
        if(currentMonthStr !== currentMonth){
            this.setState({
                currentMonth: currentMonthStr,
            });
            this.onPanelChange(ndate,"month");
        }
    }

    clickMeetingCalendarMonth(obj){
        const { eid } = this.props;
        const { selectYear, meetingtype } = this.state;
        let dateStr = formatDate(new Date(), 'MM');
        var date = formatDate(new Date(obj.time), "MM");
        const { currentDate, currentMonth } = this.state;
        let monthMatch = {
            "01" : getLabel("25825", "1月"),
            "02" : getLabel("25826", "2月"),
            "03" : getLabel("25827", "3月"),
            "04" : getLabel("25828", "4月"),
            "05" : getLabel("25829", "5月"),
            "06" : getLabel("25830", "6月"),
            "07" : getLabel("25831", "7月"),
            "08" : getLabel("25832", "8月"),
            "09" : getLabel("25833", "9月"),
            "10" : getLabel("25834", "10月"),
            "11" : getLabel("25835", "11月"),
            "12" : getLabel("25836", "12月")
        };
        let x = Math.ceil(dateStr/3);
        let y = dateStr - (x-1) * 3;
        let a = Math.ceil(date/3);
        let b = date - (a-1) * 3;
        if(monthMatch[dateStr].trim() !== parseInt(date)+'月'){
            // $("#calendar_" + eid + " .ant-fullcalendar-month-panel-cell[title='" + monthMatch[dateStr].trim() + "'] >div").addClass("ant-fullcalendar-month-panel-current-cell");
            $($($("#calendar_" + eid + " .ant-fullcalendar").find('tr')[x-1].children[y-1]).find('div')[0]).addClass("ant-fullcalendar-month-panel-current-cell");
            $("#calendar_" + eid + " .ant-fullcalendar-month-panel-selected-cell").removeClass("ant-fullcalendar-month-panel-selected-cell");
            $("#calendar_" + eid + " .ant-fullcalendar-month-panel-cell .ant-fullcalendar-value").css('border', 'none');
            $($($("#calendar_" + eid + " .ant-fullcalendar").find('tr')[a-1].children[b-1]).find('div')[0]).find(".ant-fullcalendar-value").css('border', '#2db7f5 solid 1px');
        }else {
            $("#calendar_" + eid + " .ant-fullcalendar-month-panel-cell .ant-fullcalendar-value").css('border', 'none');
            $("#calendar_" + eid + " .ant-fullcalendar-month-panel-selected-cell").removeClass("ant-fullcalendar-month-panel-selected-cell");
            // $("#calendar_" + eid).find(".ant-fullcalendar-month-panel-selected-cell").removeClass("ant-fullcalendar-month-panel-current-cell");
            $($($("#calendar_" + eid + " .ant-fullcalendar").find('tr')[x-1].children[y-1]).find('div')[0]).removeClass("ant-fullcalendar-month-panel-current-cell");
            $($($("#calendar_" + eid + " .ant-fullcalendar").find('tr')[x-1].children[y-1]).find('div')[0]).parent().addClass("ant-fullcalendar-month-panel-selected-cell");
            // $("#calendar_" + eid + " .ant-fullcalendar-month-panel-cell[title='" + monthMatch[dateStr].trim() + "'] >div").removeClass("ant-fullcalendar-month-panel-current-cell");
            $("#calendar_" + eid + " .ant-fullcalendar-month-panel-selected-cell .ant-fullcalendar-month .ant-fullcalendar-value").css('border','#2db7f5 solid 1px');
        }
        let selectMonth = '';
        for (let key in monthMatch) {
            if(monthMatch[key] == parseInt(date)+'月') {
                selectMonth =key;
                break;
            }
        }
        let firstDay =formatDate(new Date(selectYear,selectMonth-1,1),"yyyy-MM-dd");//这个月的第一天
        WeaTools.callApi('/api/meeting/calendar/getData', 'POST', {viewType: '3', selectdate: firstDay , meetingType: meetingtype }).then(data=> {
            ls.set('edata-'+eid, data);
            this.setState({
                data: data,
                refresh: false,
                firstDay: firstDay,
            });
        });
    }
}
class MyErrorHandler extends React.Component {
    render() {
        const hasErrorMsg = this.props.error && this.props.error !== "";
        return (
            <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@ugomge`} msg={hasErrorMsg?this.props.error:getLabel(385218,"对不起，该页面异常，请联系管理员！") } />
        );
    }
}
MeetingCalendarTemplate = WeaTools.tryCatch(React, MyErrorHandler, { error: "" })(MeetingCalendarTemplate);
export default MeetingCalendarTemplate;

class CalendarData extends React.Component {
    tc(d) {
        function zc(c, i) {
            var d = "666666888888aaaaaabbbbbbdddddda32929cc3333d96666e69999f0c2c2b1365fdd4477e67399eea2bbf5c7d67a367a994499b373b3cca2cce1c7e15229a36633cc8c66d9b399e6d1c2f029527a336699668cb399b3ccc2d1e12952a33366cc668cd999b3e6c2d1f01b887a22aa9959bfb391d5ccbde6e128754e32926265ad8999c9b1c2dfd00d78131096184cb05288cb8cb8e0ba52880066aa008cbf40b3d580d1e6b388880eaaaa11bfbf4dd5d588e6e6b8ab8b00d6ae00e0c240ebd780f3e7b3be6d00ee8800f2a640f7c480fadcb3b1440edd5511e6804deeaa88f5ccb8865a5aa87070be9494d4b8b8e5d4d47057708c6d8ca992a9c6b6c6ddd3dd4e5d6c6274878997a5b1bac3d0d6db5a69867083a894a2beb8c1d4d4dae54a716c5c8d8785aaa5aec6c3cedddb6e6e41898951a7a77dc4c4a8dcdccb8d6f47b08b59c4a883d8c5ace7dcce";
            return "#" + d.substring(c * 30 + i * 6, c * 30 + (i + 1) * 6);
        }
        var c = d != null && d != undefined ? d : option.theme;
        return [zc(c, 0), zc(c, 1), zc(c, 2), zc(c, 3)];
    }
    render(){
        const { data, currentDate, handleClick,eid, type = 'month', firstDay } = this.props;
        const { events } = data;
        let index = 0;
        let color = '#a32929';
        if(events && events.length) {
            if (type == 'month') {
                let hasEvent = false;
                let datas = [];
                let html = events.map(arr => {
                    if(arr[7]) color = this.tc(arr[7])[2];
                    let sdate = new Date(arr.begindate);
                    let edate = new Date(arr.enddate);
                    let startStr = formatDate(sdate, 'yyyy-MM-dd');
                    let endStr = formatDate(edate, 'yyyy-MM-dd');
                    let id = arr.id;
                    let name = arr.name;
                    let stime = arr.begintime;
                    let ss = parseInt(stime) >= 12 ? 'PM' : 'AM';
                    if (currentDate >= startStr && currentDate <= endStr) {
                        hasEvent = true;
                        index += 1;
                        return <div className='hand dataEvent' style={{height: '34px'}}
                                    onClick={handleClick.bind(this, id)} title={name}>
                            <div className='dataEvent1' style={{background: color}}></div>
                            <div className='dataEvent2'>
                                <div className='dataEvent2_1'>
                                    {stime}&nbsp;&nbsp;{ss}
                                </div>
                            </div>
                            <div class='dataEvent3'>{name}</div>
                        </div>
                    }
                });
                let height = index * 34;
                if (index < 3) {
                    return <div id={`calendar_content${eid}`}>
                        <div id='planDataEvent' className='planDataEvent'
                             style={{height: height + 1, overflowY: 'hidden', outline: 'none'}}>
                            <div id='planDataEventchd' style={{height}}>
                                {html}
                            </div>
                        </div>
                    </div>
                }
                return <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@4e1qoe`} scrollId="element_calendar_scroll" height={103}>
                    <div id={`calendar_content${eid}`}>
                        <div id='planDataEvent' className='planDataEvent'
                             style={{height: height + 1, overflowY: 'hidden', outline: 'none'}}>
                            <div id='planDataEventchd' style={{height}}>
                                {html}
                            </div>
                        </div>
                    </div>
                </WeaNewScroll>
            } else {
                if (events && events.length) {
                    let hasEvent = false;
                    let html = events.map(arr => {
                        let sdate = new Date(arr.begindate);
                        let edate = new Date(arr.enddate);
                        let id = arr.id;
                        let name = arr.name;
                        let mdata = formatDate(sdate, 'MM-dd  hh:mm')
                        const smonth = formatDate(sdate, 'MM');
                        const emonth = formatDate(edate, 'MM');
                        const firstmonth = formatDate(new Date(firstDay), 'MM');
                        if(parseInt(smonth) == parseInt(firstmonth) || parseInt(emonth)==parseInt(firstmonth) ||
                            (parseInt(smonth) <= parseInt(firstmonth) && parseInt(firstmonth)<=parseInt(emonth))){
                            let ss = parseInt(formatDate(sdate, 'hh')) >= 12 ? 'PM' : 'AM';
                            hasEvent = true;
                            index += 1;
                            return <div className='hand dataEvent' style={{height: '34px'}}
                                        onClick={handleClick.bind(this, id)} title={name}>
                                <div className='dataEvent1' style={{background: '#a32929'}}></div>
                                <div className='dataEvent2' style={{width: '111px'}}>
                                    <div className='dataEvent2_1'>
                                        {mdata}&nbsp;&nbsp;{ss}
                                    </div>
                                </div>
                                <div class='dataEvent3'>{name}</div>
                            </div>
                        }

                    });
                    let height = index * 34;
                    if (index < 3) {
                        return <div id={`calendar_content${eid}`}>
                            <div id='planDataEvent' className='planDataEvent'
                                 style={{height: height + 1, overflowY: 'hidden', outline: 'none'}}>
                                <div id='planDataEventchd' style={{height}}>
                                    {html}
                                </div>
                            </div>
                        </div>
                    }
                    return <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@9239gn`} scrollId="element_calendar_scroll" height={103}>
                        <div id={`calendar_content${eid}`}>
                            <div id='planDataEvent' className='planDataEvent'
                                 style={{height: height + 1, overflowY: 'hidden', outline: 'none'}}>
                                <div id='planDataEventchd' style={{height}}>
                                    {html}
                                </div>
                            </div>
                        </div>
                    </WeaNewScroll>
                }
            }
        }else {
            return <div/>
        }
    }
}
